package com.xthh.esl;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.xt.xthh.R;
import com.xthh.XTCore;
import com.xthh._enum.HH_EnumNfcErrorCode;
import com.xthh._function.HH_CharUtil;
import com.xthh.esl.DeviceInfo;
import com.xthh.esl.FMUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_SystemUtil;
import com.xthh._struct.HH_T_SystemParams;
import com.xthh.esl.IUtils;

import java.io.IOException;
import java.util.Arrays;

public abstract class XTBaseNFCActivity_ESL extends AppCompatActivity {
    private static final String TAG = "XTBaseNFCActivity_ESL";

    public static DeviceInfo deviceInfoeEsl;
    public static Handler mHandlerRecvEsl;

    private NfcAdapter mNfcAdapter;
    public Tag mTag;
    public int NFC_FLAG_READER = NfcAdapter.FLAG_READER_NFC_A;
    private PendingIntent mPendingIntent;
    public Handler handlerBaseNfc;
    public final int MSG_NFC_STATE = 2001;
    public HH_T_SystemParams systemParams;
    public Context mContext;


    public static ThreadRunNFCCommand gst_ThreadRunNFCCommand = null;

    @Override
    protected void onStart() {
        super.onStart();
        mContext = this;
        if (!hasNfc(this)) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.DISABLE.ordinal());
        }

        if (mNfcAdapter != null) {
            int flag = 0;
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), flag);
        }

        if (gst_ThreadRunNFCCommand == null){
            gst_ThreadRunNFCCommand = new ThreadRunNFCCommand(this);
            gst_ThreadRunNFCCommand.setRunning(true);
            gst_ThreadRunNFCCommand.start();
        }
    }

    /*String ReadNfcInfo(Tag tag){
        if (tag == null) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.ABNORMAL_TAG.ordinal());
            return null;
        }


        // 先读公司的NDEF数据
        BleNFCBindInfo nfcInfo = ReadNfcData_XT(tag);
        if (nfcInfo != null && nfcInfo.mac != null){
            HH_Logging.i(TAG, "公司的NFC；%s", nfcInfo.mac);
            return nfcInfo.mac;
        } else {
            HH_Logging.i(TAG, "错的信息或不是公司的NFC");
        }

        // 获取复旦微信息
        BleNFCBindInfo nfcInfo2 = ReadNfcData_ESL(tag);
        if (nfcInfo2 != null && nfcInfo2.mac != null)
            return nfcInfo2.mac;


        return "";
    }

    BleNFCBindInfo ReadNfcData_ESL(Tag tag){
        BleNFCBindInfo nfcInfo = new BleNFCBindInfo();
        IsoDep isoDep = IsoDep.get(tag);
        if (isoDep != null) {
            try {
                isoDep.setTimeout(50000);
                if (!isoDep.isConnected()) {
                    isoDep.connect();
                    String hexInfo = getDeviceInfo(isoDep, "");

                    DeviceInfo di = IUtils.loadDeviceInfo(hexInfo);

                    nfcInfo.mac = di.getUID();
                    // 为方便与MAC相同，强制添加到12个
                    if (nfcInfo.mac != null){
                        int n = 12 - nfcInfo.mac.length();
                        for (int i = 0; i < n; i++){
                            nfcInfo.mac += " ";
                        }
                    }


                    nfcInfo.deviceWidth = di.getWidth();
                    nfcInfo.deviceHeight = di.getHeight();
                    nfcInfo.deviceColor = di.getColor();
                    // 用这个来存详细数据，在刷图时要到到
                    nfcInfo.customSRRC = hexInfo;
                    nfcInfo.deviceNumber = XTCore.DEVICE_NUMBER_ESL;

                    HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());

                }
            } catch (Exception e) {
                e.printStackTrace();
                HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
            } finally {
                try {
                    isoDep.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return nfcInfo;
    }
*/

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && mPendingIntent != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public boolean hasNfc(Activity context) {
        NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
        mNfcAdapter = manager.getDefaultAdapter();
        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            return true;
        }
        return false;
    }


    public void GetNFCCardInfo(HH_T_SystemParams sp, boolean autoNfcClose){
        systemParams = sp;
        if (mNfcAdapter != null){
            mNfcAdapter.disableReaderMode(this);
        }
    }

    public void startReaderMode() {
        Bundle bundle = new Bundle();
        bundle.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 0);
        mNfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
            @Override
            public void onTagDiscovered(Tag tag) {
                String[] techList = tag.getTechList();
                for (int i = 0; i < techList.length; i++) {
                    //LogUtil.d(techList[i]);

                }
                mTag = tag;
                Bundle bundle = new Bundle();
                bundle.putParcelable(NfcConstant.KEY_TAG, mTag);
                BroadcastManager.getInstance(mContext).sendBroadcast(NfcConstant.KEY_TAG, bundle);
            }

        }, NFC_FLAG_READER, null);
    }

    public void refreshNfc(){
        if(mNfcAdapter.isEnabled()){
            // 关闭reader 模式主动调用NFC回调一次
            mNfcAdapter.disableReaderMode(this);
        }
        startReaderMode();
    }




    public void NFCCommand(HH_T_SystemParams tps, CommandNFC commandNFC, int msg, String path, DeviceInfo bindInfo){
        BroadcastManager.getInstance(tps.getCtx()).destroy(NfcConstant.KEY_TAG);
        BroadcastManager.getInstance(tps.getCtx()).addAction(NfcConstant.KEY_TAG, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                NFCTask nfcTask = new NFCTask(mTag, commandNFC, tps, msg, path, bindInfo);
                if (gst_ThreadRunNFCCommand != null){
                    gst_ThreadRunNFCCommand.addTask(nfcTask);
                }

            }
        });

        // 刷新NFC
        refreshNfc();
    }
}
